package com.tjetc.service;

import com.tjetc.model.ChatResponse;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;

@Service
public class TaskManager {

    // 存储任务状态和结果
    private final Map<String, TaskInfo> taskMap = new ConcurrentHashMap<>();

    // 线程池处理AI请求
    private final ExecutorService executorService = Executors.newFixedThreadPool(5);

    // 初始化定时任务
    @PostConstruct
    public void init() {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        // 每小时执行一次清理
        scheduler.scheduleAtFixedRate(this::cleanupOldTasks, 1, 1, TimeUnit.HOURS);
        System.out.println("任务清理定时器已启动");
    }

    // 任务信息类
    public static class TaskInfo {
        public enum Status {
            PENDING, PROCESSING, COMPLETED, FAILED
        }

        private Status status;
        private ChatResponse result;
        private String errorMessage;
        private final long createdTime;  // 添加创建时间字段

        public TaskInfo() {
            this.status = Status.PENDING;
            this.createdTime = System.currentTimeMillis();  // 记录创建时间
        }

        // Getters and setters
        public Status getStatus() {
            return status;
        }

        public void setStatus(Status status) {
            this.status = status;
        }

        public ChatResponse getResult() {
            return result;
        }

        public void setResult(ChatResponse result) {
            this.result = result;
        }

        public String getErrorMessage() {
            return errorMessage;
        }

        public void setErrorMessage(String errorMessage) {
            this.errorMessage = errorMessage;
        }

        public long getCreatedTime() {
            return createdTime;
        }
    }

    // 创建新任务
    public String createTask() {
        String taskId = UUID.randomUUID().toString();
        taskMap.put(taskId, new TaskInfo());
        return taskId;
    }

    // 获取任务状态和结果
    public TaskInfo getTaskInfo(String taskId) {
        return taskMap.get(taskId);
    }

    // 提交AI任务到线程池
    public void submitTask(String taskId, Runnable task) {
        TaskInfo taskInfo = taskMap.get(taskId);
        if (taskInfo != null) {
            taskInfo.setStatus(TaskInfo.Status.PROCESSING);
            executorService.submit(task);
        }
    }

    // 任务完成后清理
    public void cleanupOldTasks() {
        final long retentionPeriod = 24 * 60 * 60 * 1000L; // 24小时（毫秒）
        long now = System.currentTimeMillis();
        int removedCount = 0;

        // 遍历并删除旧任务
        for (Map.Entry<String, TaskInfo> entry : taskMap.entrySet()) {
            TaskInfo info = entry.getValue();

            // 清理已完成或失败且超过保留期的任务
            if ((info.getStatus() == TaskInfo.Status.COMPLETED ||
                    info.getStatus() == TaskInfo.Status.FAILED) &&
                    (now - info.getCreatedTime() > retentionPeriod)) {

                taskMap.remove(entry.getKey());
                removedCount++;
            }
        }

        if (removedCount > 0) {
            System.out.println(Instant.now() + " - 清理了 " + removedCount + " 个旧任务。当前任务数量: " + taskMap.size());
        }
    }
}